#coding=utf-8
__author__ = 'jy@cjlu.edu.cn'
#=======================================================================================================================
#功能编号:[0011]
#功能名称:公司信息管理
#功能:主要用于管理集团各子公司及本级的基础信息
#=======================================================================================================================
from iLibP.loger import *
from basehandler import basehandler
from config import *
from SysCommon.exceloperator import ExcelOperator
from SysCommon.tools import *
from models.d_incinfo import *
import json
from CODES import CODES1#引入公司类型
from models import s_no
def SqlWhereStr(i):
    """
    专门用于生成where条件,根据实际情况修改
    """
    fields=[
        "incname",
        ]
    i=InitStorageBlank(i,fields)
    strwhere=" id>0 "
    if i.incname:
        strwhere+=" and incname='"+i.incname+"'"
    return strwhere

def DataFilter(i):
    obj=bll_d_incinfo()
    i.pageindex=i.get("pageindex",0)            #指定默认值
    i.pagesize=i.get("pagesize",13)             #指定默认值
    i.rc=0
    i.pc=0
    i.recs=[]
    #补充其他查询条件
    strwhere=SqlWhereStr(i)
    i.recs,i.rc,i.pc=obj.GetPagedRowsByDbWhere(i.pageindex,i.pagesize,where=strwhere)
    i.recs=i.recs.list()
    return i

class Ajax(basehandler):
    def get(self):
        self.set_header("Content-Type", "text/html; charset=UTF-8")
        i=self.input()
        cmd=i.get("act","")
        if cmd=="ajax1":               #用于查询数据
            i=DataFilter(i)
            t=global_lookup.get_template("f00/T/TT/f0011_ajax1.html")
            self.write(t.render(i=i))
    def post(self):
        self.set_header("Content-Type", "application/json; charset=UTF-8")
        i=self.input()
        cmd=i.get("act","")
        obj=bll_d_incinfo()
        if cmd=="del":
            if i.id:
                obj.DelRowById(i.id)
                self.write(json.dumps({"result":"OK"}))
        if  cmd=="add":
            i.id=0
            obj.Save(i)
            return json.dumps({"result":"OK"})
        if cmd=="edit":
            obj.Save(i)
            return json.dumps({"result":"OK"})
        if cmd=="save":#用于保存即时编辑数据
            if i.id and i.value:
                try:
                    col=str(i.id).split('_')[0]
                    id=str(i.id).split('_')[1]
                    rec=obj.GetRowById(id)
                    rec[col]=i.value
                    obj.SaveEx(rec,["id",col])
                    self.write(rec[col])
                except :
                    self.write("")

class List(basehandler):
    """
    用于处理列表页面或默认显示页面
    对于数据的删除或简单AJAX的操作也放置在此类中，
    可放置于post函数内
    """
    def get(self):
        self.set_header("Content-Type", "text/html; charset=UTF-8")
        i=self.input()
        cmd=i.get("act","list")
        if cmd=="list":
            t=global_lookup.get_template("f00/T/f0011_list.html")
            i=DataFilter(i)
            self.write(t.render(i=i))
        if cmd=="update":
            obj=bll_d_incinfo()
            t=global_lookup.get_template("f00/T/f0011_update.html")
            i.CODES=CODES1
            if i.get("id",None):
                i.rec=obj.GetRowById(i.id)
            else:
                #企业编号的字头定义为INCNO
                i.incno=s_no.GC_COUNT("INCNO",4,False)
            self.write(t.render(i=i))
    def post(self):
        self.set_header("Content-Type", "text/html; charset=UTF-8")
        i=self.input()
        cmd=i.get("act","list")
        if cmd=="search":
            t=global_lookup.get_template("f00/T/f0011_list.html")
            i=DataFilter(i)
            self.write(t.render(i=i))

class Import(basehandler):
    def get(self):
        self.set_header("Content-Type", "text/html; charset=UTF-8")
        #请修改路径
        t=global_lookup.get_template("f00/T/f0011_import.html")
        self.write(t.render())

    def post(self):
        self.set_header("Content-Type", "text/html; charset=UTF-8")
        i=self.input()
        optobj=bll_d_incinfo()
        #1.导入数据时只做更新操作，特别注意不能删除数据
        t=optobj.Transaction()
        eo=ExcelOperator()                          #file控件名要为excel
        f=eo.uploadFile(i)
        result=eo.parseExcel(f)
        importresult=[]
        try:
            for d in result.data:
                #查找部分数据
                try:
                    #修改查询条件
                    strwhere="employeeno='"+d.employeeno+"'"
                    rec=optobj.GetRowByStrWhere(strwhere)
                    if rec:#找到更新
                        d=CopyData(rec,d)
                        #补充需要更新的列名
                        optobj.SaveEx(d,["id",""])
                        d.importstatus=u"【成功】更新"
                    else:#找不到则写入
                        d.id=0
                        optobj.Save(d)
                        d.importstatus=u"【成功】写入"
                except Exception,ex1:
                    print ex1
                    d.importstatus=u"【失败】数据异常"
                importresult.append(d)
            optobj.Commit(t)
            t=global_lookup.get_template("f00/T/f0011_importresult.html")
            self.write(t.render(datas=importresult))
        except Exception,ex:
            msg=u"iLib执行Save函数出错,[具体信息]:"+str(ex)
            LogError(msg)
            optobj.RollBack(t)
            raise Exception,msg

class Export(basehandler):
    """
    用于将数据导出向EXCEL
    """
    def post(self):
        self.set_header("Content-Type", "application/json; charset=UTF-8")
        i=self.input()
        from SysCommon.exceloperator import ExcelOperator
        excelobj=ExcelOperator()
        wb,ws=excelobj.openExistExcel(TP_PATH+"/static/T/f0011.xls")
        start_row=3
        #1.获取数据
        bjobj=bll_d_incinfo()
        strwhere=SqlWhereStr(i)
        datas=bjobj.GetRowsByStrWhere(strwhere)
        #2.组合excel
        for d in datas:
            ws.write(start_row,0,d.parentinc)
            ws.write(start_row,1,d.incname)
            ws.write(start_row,2,d.addressdetail)
            ws.write(start_row,3,d.postno)
            ws.write(start_row,4,d.personincharge)
            ws.write(start_row,5,d.phoneno)
            ws.write(start_row,6,d.emailaddress)
            ws.write(start_row,7,d.inctype)
            ws.write(start_row,8,d.bz1)
            start_row+=1
            #3.输出excel
        nfilename="/static/tmpfiles/f0011_"+TimeStr()+".xls"
        wb.save(TP_PATH+nfilename)
        self.write(JsonResult(nfilename))